package com.cyx.netty.c1;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class TestFileChannelTransferTo {
    public static void main(String[] args) throws Exception{
        /*
        FileChannel传输数据
         */
        File fromFile = ResourceUtils.getFile("classpath:ttData.txt");
        File toFile = ResourceUtils.getFile("classpath:ttTo.txt");
        try (
                FileChannel from = new FileInputStream(fromFile).getChannel();
                FileChannel to = new FileOutputStream(toFile).getChannel()
        ) {
            // 效率高，底层会利用操作系统的零拷贝进行优化 传输有上线，一次最多传2G数据
            long size = from.size();
            // left 变量代表还剩余多少字节
            for (long left = size; left > 0; ) {
                left -= from.transferTo((size - left), left, to);
            }
//            from.transferTo(0, from.size(), to);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
